﻿Imports Windows.UI.Xaml.Media.Animation

''' <summary>
''' An empty page that can be used on its own or navigated to within a Frame.
''' </summary>
Public NotInheritable Class MainPage
    Inherits Page

    Dim WithEvents SB As MMGameLibrary2D.ScrollableBackground       'ScrollableBackground object
    Dim mySprite As MMGameLibrary2D.Sprite                          'Sprite object for player character
    Dim GameLoopStoryboard As Storyboard                            'Storyboard used as a timer for game loop

    Dim upButtonPressed As Boolean = False
    Dim downButtonPressed As Boolean = False
    Dim leftButtonPressed As Boolean = False
    Dim rightButtonPressed As Boolean = False

    Dim controller As New SharpDX.XInput.Controller(SharpDX.XInput.UserIndex.One)

#Region "PAGE EVENTS"

    ''' <summary>
    ''' Invoked when this page is about to be displayed in a Frame.
    ''' </summary>
    ''' <param name="e">Event data that describes how this page was reached.  The Parameter
    ''' property is typically used to configure the page.</param>
    Protected Overrides Async Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)

        'Create new ScrollableBackground instance
        SB = New MMGameLibrary2D.ScrollableBackground(1366, 768, MMGameLibrary2D.ScrollableBackground.enScrollDirection.RightToLeft)

        'Enable collisions pixel-pixel (ADVANCED)
        SB.CollisionDetectionLevel = MMGameLibrary2D.ScrollableBackground.enCollisionDetectionLevel.AUTO_ADVANCED

        'Create new layer for the sky level
        Dim bi As New BitmapImage(New Uri("ms-appx:///Assets/sky.jpg"))
        Dim bl As New MMGameLibrary2D.BackgroundLayer(New Point(0, 0), 1366, 300, bi)
        bl.Key = "sky"
        'Add "Sky" layer to ScrollableBackground instance
        SB.AddLayer(bl)

        'Create new layer for the mountains level
        bi = New BitmapImage(New Uri("ms-appx:///Assets/mountains.png"))
        bl = New MMGameLibrary2D.BackgroundLayer(New Point(0, 0), 1366, 768, bi)
        bl.Key = "mountains"
        'Add "mountains" layer to ScrollableBackground instance
        SB.AddLayer(bl)

        'Create new layer for the hills level
        bi = New BitmapImage(New Uri("ms-appx:///Assets/hills.png"))
        bl = New MMGameLibrary2D.BackgroundLayer(New Point(0, 450), 1366, 350, bi)
        bl.Key = "hills"
        'Add "hills" layer to ScrollableBackground instance
        SB.AddLayer(bl)

        'Create new layer for the grass level
        bi = New BitmapImage(New Uri("ms-appx:///Assets/grass.png"))
        bl = New MMGameLibrary2D.BackgroundLayer(New Point(0, 650), 1366, 120, bi)
        bl.Key = "grass"
        'Add "grass" layer to ScrollableBackground instance
        SB.AddLayer(bl)

        'Add canvas generated by ScrollableBackground class to the main container of this page
        Me.mainGrid.Children.Add(SB.BackgroundCanvas)
        Grid.SetRow(SB.BackgroundCanvas, 1)

        'Create new sprite object for main character
        mySprite = New MMGameLibrary2D.Sprite(102, 105, New Point(100, 200))
        'set a key to identify this object in sprites collection
        mySprite.Key = "helloKitty"
        'set the "type" of sprite. (This is useful in collision detection)
        mySprite.SpriteType = "personaggio"
        'Enable collision detection for this sprite
        mySprite.isCollisionEnabled = True
        'Add spritesheet image
        Await mySprite.SetSpriteSheet(New Uri("ms-appx:///Assets/helloKitty_spritesheet.png"), 3, 2)
        'Add an animation named "sciarpa" with restart behavior and forward direction
        mySprite.AddAnimation("sciarpa", 0, 0, 0, 1, MMGameLibrary2D.SpriteAnimation.enLoopBehaviorType.RESTART, MMGameLibrary2D.SpriteAnimation.enAnimationDirection.FORWARD)

        'Add "helloKitty" sprite to ScrollableBackground instance
        SB.AddSprite(mySprite)

        'Create some enemy sprites
        Dim rn As New Random()
        For i As Integer = 1 To 10
            Dim x As Double = rn.Next(0, 1300)
            Dim y As Double = rn.Next(0, 700)

            mySprite = New MMGameLibrary2D.Sprite(71, 99, New Point(x, y))
            mySprite.Key = "enemy" & i.ToString
            mySprite.SpriteType = "nemico"
            mySprite.isCollisionEnabled = True
            'Add spritesheet image
            Await mySprite.SetSpriteSheet(New Uri("ms-appx:///Assets/bomb.tif"), 1, 1)
            'Add "enemy" sprite to ScrollableBackground instance
            SB.AddSprite(mySprite)
        Next i

        'add a gamepad
        Dim gp As New MMGameLibrary2D.AnalogicGamePad '(MMGameLibrary2D.GamePad.enGamepadType.DIRECTIONAL_4)
        AddHandler gp.StickPositionChanged, AddressOf Gamepad_ValueChanged
        SB.BackgroundCanvas.Children.Add(gp)

        'gameloop initialization
        GameLoopStoryboard = New Storyboard
        GameLoopStoryboard.Duration = TimeSpan.FromMilliseconds(0)
        AddHandler GameLoopStoryboard.Completed, AddressOf GameLoop

    End Sub

    Private Sub MainPage_KeyDown(sender As Object, e As KeyRoutedEventArgs) Handles Me.KeyDown

        Select Case e.Key
            Case Windows.System.VirtualKey.Left
                leftButtonPressed = True
            Case Windows.System.VirtualKey.Right
                rightButtonPressed = True
            Case Windows.System.VirtualKey.Up
                upButtonPressed = True
            Case Windows.System.VirtualKey.Down
                downButtonPressed = True
        End Select

    End Sub

    Private Sub MainPage_KeyUp(sender As Object, e As KeyRoutedEventArgs) Handles Me.KeyUp

        Select Case e.Key
            Case Windows.System.VirtualKey.Left
                leftButtonPressed = False
            Case Windows.System.VirtualKey.Right
                rightButtonPressed = False
            Case Windows.System.VirtualKey.Up
                upButtonPressed = False
            Case Windows.System.VirtualKey.Down
                downButtonPressed = False

        End Select

    End Sub

    Private Sub Gamepad_ValueChanged(horizontalValue As Integer, verticalValue As Integer)

        If horizontalValue > 0 Then
            rightButtonPressed = True
            leftButtonPressed = False
        ElseIf horizontalValue < 0 Then
            rightButtonPressed = False
            leftButtonPressed = True
        Else
            rightButtonPressed = False
            leftButtonPressed = False
        End If

        If verticalValue > 0 Then
            upButtonPressed = False
            downButtonPressed = True
        ElseIf verticalValue < 0 Then
            upButtonPressed = True
            downButtonPressed = False
        Else
            upButtonPressed = False
            downButtonPressed = False
        End If

    End Sub

#End Region

#Region "CONTROLS EVENTS"

    Private Sub startButton_Click(sender As Object, e As RoutedEventArgs) Handles startButton.Click

        'Set layers speedrate
        SB.ScrollSpeed = CType(speedSlider.Value, Integer)
        SB.LayerItem("sky").SpeedRate = 5
        SB.LayerItem("mountains").SpeedRate = 15
        SB.LayerItem("hills").SpeedRate = 30
        SB.LayerItem("grass").SpeedRate = 80

        'Start background scroll
        SB.StartScroll()

        'Start main character animation
        SB.SpriteItem("helloKitty").StartAnimation("sciarpa", 25)

        GameLoopStoryboard.Begin()

    End Sub

    Private Sub stopButton_Click(sender As Object, e As RoutedEventArgs) Handles stopButton.Click

        SB.StopScroll()
        SB.SpriteItem("helloKitty").StopAnimation()
        GameLoopStoryboard.Stop()

    End Sub

    Private Sub pauseButton_Click(sender As Object, e As RoutedEventArgs) Handles pauseButton.Click

        SB.PauseScroll()
        SB.SpriteItem("helloKitty").StopAnimation()
        GameLoopStoryboard.Stop()

    End Sub

    Private Sub speedSlider_ValueChanged(sender As Object, e As RangeBaseValueChangedEventArgs) Handles speedSlider.ValueChanged

        SB.ScrollSpeed = CType(speedSlider.Value, Integer)

        startButton.Focus(Windows.UI.Xaml.FocusState.Programmatic)

    End Sub

    Private Sub switchDirectionOptions_Checked(sender As Object, e As RoutedEventArgs) Handles rightToLeftOption.Checked, leftToRightOption.Checked, BottomToTopOption.Checked, TopToBottomOption.Checked

        Select Case sender.name
            Case rightToLeftOption.Name
                SB.SwitchScrollDirection(MMGameLibrary2D.ScrollableBackground.enScrollDirection.RightToLeft, 1)
            Case leftToRightOption.Name
                SB.SwitchScrollDirection(MMGameLibrary2D.ScrollableBackground.enScrollDirection.LeftToRight, 1)
            Case TopToBottomOption.Name
                SB.SwitchScrollDirection(MMGameLibrary2D.ScrollableBackground.enScrollDirection.TopToBottom, 1)
            Case BottomToTopOption.Name
                SB.SwitchScrollDirection(MMGameLibrary2D.ScrollableBackground.enScrollDirection.BottomToTop, 1)
        End Select

    End Sub

#End Region

#Region "BACKGROUND EVENTS"

    Private Sub CollisionDetect(sprite1 As MMGameLibrary2D.Sprite, sprite2 As MMGameLibrary2D.Sprite) Handles SB.CollisionDetect

        'If a collision occurs between main character and an enemy,
        'simply remove the enemy sprite from sreen
        If sprite1.SpriteType = "nemico" Then
            SB.RemoveSprite(sprite1)
        End If

        If sprite2.SpriteType = "nemico" Then
            SB.RemoveSprite(sprite2)
        End If

    End Sub

#End Region

#Region "Private Functions"

    Private Sub GameLoop(sender As Object, e As Object)

        Dim keyStroke As SharpDX.XInput.Keystroke = Nothing
        Dim st As SharpDX.XInput.State = Nothing

        If controller.IsConnected = True Then
            Try
                st = controller.GetState
            Catch
                st.PacketNumber = 0
            End Try

            If st.PacketNumber <> 0 Then

                upButtonPressed = (st.Gamepad.LeftThumbY < SharpDX.XInput.Gamepad.LeftThumbDeadZone)
                downButtonPressed = (st.Gamepad.LeftThumbY > SharpDX.XInput.Gamepad.LeftThumbDeadZone)
                leftButtonPressed = (st.Gamepad.LeftThumbX < SharpDX.XInput.Gamepad.LeftThumbDeadZone)
                rightButtonPressed = (st.Gamepad.LeftThumbX > SharpDX.XInput.Gamepad.LeftThumbDeadZone)
            Else
                upButtonPressed = False
                downButtonPressed = False
                leftButtonPressed = False
                rightButtonPressed = False
            End If
        End If


        If leftButtonPressed Then
            'move sprite back to 4 pixels and reset rotation
            SB.SpriteItem("helloKitty").Move(New Point(SB.SpriteItem("helloKitty").Position.X - 4, SB.SpriteItem("helloKitty").Position.Y))
            SB.SpriteItem("helloKitty").Rotate(0)
        End If
        If rightButtonPressed Then
            'move sprite forward to 4 pixels and reset rotation
            SB.SpriteItem("helloKitty").Move(New Point(SB.SpriteItem("helloKitty").Position.X + 4, SB.SpriteItem("helloKitty").Position.Y))
            SB.SpriteItem("helloKitty").Rotate(0)
        End If
        If upButtonPressed Then
            'move sprite up to 4 pixels and set a rotation of -30 degrees
            SB.SpriteItem("helloKitty").Move(New Point(SB.SpriteItem("helloKitty").Position.X, SB.SpriteItem("helloKitty").Position.Y - 4))
            SB.SpriteItem("helloKitty").Rotate(-30)
        End If
        If downButtonPressed Then
            'move sprite down to 4 pixels and set a rotation of 30 degrees
            SB.SpriteItem("helloKitty").Move(New Point(SB.SpriteItem("helloKitty").Position.X, SB.SpriteItem("helloKitty").Position.Y + 4))
            SB.SpriteItem("helloKitty").Rotate(30)
        End If

        'restart gameloop
        GameLoopStoryboard.Begin()

    End Sub

#End Region

End Class
